import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:demo1/pages/conversation/chatdetail_ui.dart';
import 'package:demo1/provider/_providers.dart';
import '../../model/_models_chat.dart';
import 'conversation_item_ui.dart';


class ChatPage extends ConsumerWidget {

  ChatPage({super.key});


  Function(Conversation item, int index)? onPress;


  @override
  Widget build(BuildContext context, WidgetRef ref) {

    print("ChatPage:build");

    return Consumer(
        builder: (context, ref, child) {

          return buildBodyLayout(context, ref);
        }
    );
  }

  Widget buildBodyLayout(BuildContext context,
      WidgetRef ref) {

    var conversations = ref.watch(chatManagerProvider).conversations;
    int chatIndex = ref.read(chatManagerProvider).chatIndex;

    onPress = (item, index) {
      ref.read(chatManagerProvider).changeChat(item);
    };

    final _screen = MediaQuery
        .of(context)
        .size;

    var items = Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Container(
            width: _screen.width * 0.25,
            child: buildConvasationList(conversations,chatIndex)),
        VerticalDivider(width: 1.0),
        Expanded(child: IndexedStack(index: chatIndex,children: [
            for(Conversation c in conversations) buildChatDetail(ref,c)
        ],)),
      ],
    );

    return items;
  }

   buildChatDetail(WidgetRef ref,Conversation conversation) {

    return ChatdetailUI(chatDetailProvider: ref.read(chatManagerProvider).getChatDetailProvider(conversation.sessionId),);
  }

  Widget buildConvasationList(List<Conversation> conversations,int chatIndex) {


    return Scaffold(
      appBar: AppBar(
        toolbarHeight: 35,
        shadowColor: Colors.transparent,
        title: const Text(
          '消息',
          style: TextStyle(color: Colors.white, fontSize: 18),
        ),
        actions: [],
      ),
      // ignore: avoid_unnecessary_containers
      body: Container(
          child: ListView.builder(
            itemBuilder: (BuildContext context, int index) {
              return ConversationItem(
                conversations[index],
                index,
                0,
                (index == chatIndex),
                onPress,
              );
            },
            itemCount: conversations.length,
          )),
    );
  }
}



